<template>
  <div>
    <p @click="toggleRoadState">实时路况</p>
    <el-card class="legend" v-if="isShowLegend">
      <div class="legend-item">
        <span>拥堵</span>
        <div class="item red"></div>
      </div>
      <div class="legend-item">
        <span>缓慢</span>
        <div class="item yellow"></div>
      </div>
      <div class="legend-item">
        <span>畅通</span>
        <div class="item green"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
let $map = null;
//获取图层文档的要素
let features = null;
//切换实时路况状态的参数
let isShowRoadState = false;
let layer = null;
onMounted(() => {
  $map = inject("$map");
});
//利用封装的Query函数从图层文档获取要素
import { Query } from "../../utils/Query";
let service = {
  name: "guanggu",
  layerId: 1,
};
const success = (data) => {
  let format = new Zondy.Format.PolygonJSON();
  features = format.read(data);
};
Query.queryByLayer({
  service,
  success,
});
let isShowLegend = ref(false)
//切换是否显示实时路况的函数
function toggleRoadState() {
  isShowRoadState = !isShowRoadState;
  isShowLegend.value = !isShowLegend.value
  if (isShowRoadState) {
    showRoadState();
  } else {
    hideRoadState();
  }
}
//显示实时路况图层的函数
function showRoadState() {
  // console.log(features)
  features.forEach((item) => {
    let color = null;
    var flow = item.values_.values_["车流量"];
    if (flow > 1500) {
      color = "red";
    } else if (flow > 1000) {
      color = "yellow";
    } else {
      color = "green";
    }
    let stateStyle = new ol.style.Style({
      stroke: new ol.style.Stroke({
        width: 6,
        color,
      }),
    });
    item.setStyle(stateStyle);
  });

  var source = new ol.source.Vector({
    features,
  });
  layer = new ol.layer.Vector({
    source,
  });
  $map.addLayer(layer);
}
//移除实时路况图层的函数
function hideRoadState() {
  $map.removeLayer(layer);
}

</script>

<style scoped lang="scss">
.legend {
  /* 现有样式 */
  width: 150px;
  position: fixed;
  top: 80px;
  left: 50px;
  /* 添加渐变背景 */
  background: linear-gradient(270deg, #6589b6, #3a77c2);
  opacity: 0.8;
  border-radius: 20px;
  border: 2px solid #4e71a8;
}
.legend-item {
  display: flex;
  height: 30px;
  span {
    color: white;
    margin-right: 10px;
    display: block;
    line-height: 30px;
  }

  .item {
    width: 60px;
    height: 10px;
    margin-top: 10px;
  }

  .red {
    background-color: red;
  }

  .yellow {
    background-color: yellow;
  }

  .green {
    background-color: green;
  }
}
</style>
